import type { PluginOption, ViteDevServer } from "vite";
import axios from "axios";
import colors from "picocolors";
import { createSign, createTimes } from "../utils/util";
import md5 from "js-md5";
import {ResultEnum} from "../enums/httpEnum";

export default function vitePluginVueMonitor(viteEnv: ViteEnv, mode: string): PluginOption {
	return {
		name: "check-dev",
		enforce: "pre",
		configureServer(server: ViteDevServer) {
			const print = server.printUrls;
			server.printUrls = () => {
				let params = { timestamp: createTimes() };
				axios
					.get(
						`${viteEnv.VITE_API_PROXY_URL ? viteEnv.VITE_API_PROXY_URL : viteEnv.VITE_API_URL}${
							viteEnv.VITE_PREFIX_API
						}/dev/account/check`,
						{
							params,
							headers: {
								sign: createSign(params, (str: string) => md5(str))
							}
						}
					)
					.then(function (response) {
						if (response.status === 200) {
							if (response.data.code !== ResultEnum.SUCCESS) {
								console.log(response.config.url);
								console.log(response.data);
								return;
							}
							console.log(
								"\n",
								colors.yellow("  " + mode + "环境"),
								colors.yellow(" 账号:" + response.data.data.username),
								colors.yellow(" 密码:" + response.data.data.password),
								"\n\n"
							);
						} else {
							console.log(response.status);
							console.log(response.data);
							console.log(response.config.url);
						}
					})
					.catch(function (error) {
						console.log(error);
					});
				print();
			};
		}
	};
}
